// ----------------------- 图表概览 -----------------------
// 学生列表渲染请求
function studentList() {
	axios.get('/student/overview').then(({data: {code, data, message}}) => {
		// console.log(data)
		qs('.overview .total').innerHTML = data.total
		qs('.overview .avgSalary').innerHTML = data.avgSalary
		qs('.overview .avgAge').innerHTML = data.avgAge
		qs('.overview .proportion').innerHTML = data.proportion
	})
}
studentList()
// ----------------------- 饼图 -----------------------
function pie(pieData) {
	const myChart = echarts.init(document.querySelector('.pie'))
	myChart.setOption({
		tooltip: {
    },
		title: {
			text: '籍贯 Hometown',
			left: 'left'
		},
		toolbox: {
			show: true,
			feature: {
				mark: { show: true },
			}
		},
		series: [
			{
				name: 'Nightingale Chart',
				type: 'pie',
				radius: [10, 130],
				center: ['50%', '50%'],
				// roseType: 'area',
				itemStyle: {
					borderRadius: 8
				},
				data: pieData
			}
		]
	})
}
// ----------------------- 地图 -----------------------

function myMap(chinaGeoCoordMap, chinaDatas) {
 
	let convertData = function(data) {
		let res = [];
		for(let i = 0; i < data.length; i++) {
			let dataItem = data[i];
			let fromCoord = chinaGeoCoordMap[dataItem[0].name];
			let toCoord = [121.4648, 31.2891];
			if(fromCoord && toCoord) {
				res.push([{
					coord: fromCoord,
					value: dataItem[0].value
				}, {
					coord: toCoord,
				}]);
			}
		}
		return res;
	};
	let series = [];
	[['上海', chinaDatas]].forEach(function(item, i) {
	    // console.log(item)
		series.push({
				type: 'lines',
				zlevel: 2,
				effect: {
					show: true,
					period: 4, //箭头指向速度，值越小速度越快
					trailLength: 0.02, //特效尾迹长度[0,1]值越大，尾迹越长重
					symbol: 'arrow', //箭头图标
					symbolSize: 5, //图标大小
				},
				lineStyle: {
					normal: {
						width: 1, //尾迹线条宽度
						opacity: 1, //尾迹线条透明度
						curveness: .3 //尾迹线条曲直度
					}
				},
				data: convertData(item[1])
			}, {
				type: 'effectScatter',
				coordinateSystem: 'geo',
				zlevel: 2,
				rippleEffect: { //涟漪特效
					period: 4, //动画时间，值越小速度越快
					brushType: 'stroke', //波纹绘制方式 stroke, fill
					scale: 4 //波纹圆环最大限制，值越大波纹越大
				},
				label: {
					normal: {
						show: true,
						position: 'right', //显示位置
						offset: [5, 0], //偏移设置
						formatter: function(params){//圆环显示文字
							return params.data.name;
						},
						fontSize: 13
					},
					emphasis: {
						show: true
					}
				},
				symbol: 'circle',
				symbolSize: function(val) {
					return 5+ val[2] * 5; //圆环大小
				},
				itemStyle: {
					normal: {
						show: false,
						color: '#f00'
					}
				},
				data: item[1].map(function(dataItem) {
					return {
						name: dataItem[0].name,
						value: chinaGeoCoordMap[dataItem[0].name].concat([dataItem[0].value])
					};
				}),
			},
			//被攻击点
			{
				type: 'scatter',
				coordinateSystem: 'geo',
				zlevel: 2,
				rippleEffect: {
					period: 4,
					brushType: 'stroke',
					scale: 4
				},
				label: {
					normal: {
						show: true,
						position: 'right',
						//offset:[5, 0],
						color: '#0f0',
						formatter: '{b}',
						textStyle: {
							color: "#0f0"
						}
					},
					emphasis: {
						show: true,
						color: "#f60"
					}
				},
				symbol: 'pin',
				symbolSize: 50,
				data: [{
					name: item[0],
					value: chinaGeoCoordMap[item[0]].concat([10]),
				}],
			}
		);
	});
  const myChart = echarts.init(document.querySelector('.map'))
  myChart.setOption({
		title: {
			text: '来沪路线',
		},
		tooltip: {
			trigger: 'item',
			backgroundColor: 'rgba(166, 200, 76, 0.82)',
			borderColor: '#FFFFCC',
			showDelay: 0,
			hideDelay: 0,
			enterable: true,
			transitionDuration: 0,
			extraCssText: 'z-index:100',
			formatter: function(params, ticket, callback) {
				//根据业务自己拓展要显示的内容
				let res = "";
				let name = params.name;
				let value = params.value[params.seriesIndex + 1];
				res = "<span style='color:#fff;'>" + name + "</span><br/>数据：" + value;
				return res;
			}
		},
		backgroundColor:"#fff",
		visualMap: { //图例值控制
			min: 0,
			max: 1,
			calculable: true,
			show: false,
			color: ['#f44336', '#fc9700', '#ffde00', '#ffde00', '#00eaff'],
			textStyle: {
				color: '#fff'
			}
		},
		geo: {
			map: 'china',
			zoom: 1.2,
			label: {
				emphasis: {
					show: false
				}
			},
			roam: true, //是否允许缩放
			itemStyle: {
				normal: {
					color: 'rgba(51, 69, 89, .5)', //地图背景色
					borderColor: '#516a89', //省市边界线00fcff 516a89
					borderWidth: 1
				},
				emphasis: {
					color: 'rgba(37, 43, 61, .5)' //悬浮背景
				}
			}
		},
		series: series
	})
}
// myMap()
//  ----------------------- 柱状图 -----------------------
// 封装柱状图的请求
function barApi(batch = 1) {
	axios.get('/score/batch', {
		params: {
			batch
		}
	}).then(({data: {code, message, data}}) => {
		if (code === 0) {
			// console.log(data)
			bar(data)
		}else {
			alert(message)
		}
	})
}
barApi()
function bar({avgScore, group, gt60, gt80, lt60}) {
const myChart = echarts.init(document.querySelector('.barChart'))
const colors = ['blue', '#91CC75', 'yellow', 'orangered']
myChart.setOption({
  color: colors,
  grid: {
    left: '4%',
    right: '4%',
    top: '10%',
    bottom: '3%',
    containLabel: true
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross'
    }
  },
  legend: {
  },
  xAxis: [
    {
      type: 'category',
      axisPointer: {
        // 坐标轴指示器为阴影，配合tooltip中的设置，组成十字准星
        type: 'shadow',
      },
      data: group
    }
  ],
  yAxis: [
    {
      type: 'value',
      min: 0,
      max: 100,
      interval: 10,
      position: 'left',
      axisLabel: {
        formatter: '{value}分'
      }
    },
    {
      type: 'value',
      min: 0,
      max: 10,
      interval: 1,
      position: 'right',
      axisLabel: {
        formatter: '{value}人'
      }
    }
  ],
  series: [
    {
      name: '平均分',
      type: 'bar',
      data: avgScore
    },
    {
      name: '低于60分人数',
      type: 'bar',
      data: lt60,
			// 让图更好看一些
			yAxisIndex: 1
    },
    {
      name: '60到80分之间',
      type: 'bar',
      data: gt60,
			yAxisIndex: 1
    },
    {
      name: '高于80分人数',
      type: 'bar',
      data: gt80,
			yAxisIndex: 1
    }
  ]
})
}
//--------右侧菜单栏功能
// 点击菜单栏显示考试成绩
qs('.btn').onclick = function () {
	qs('#batch').classList.toggle('show')
}
// 遍历注册点击事件
qsAll('#batch li').forEach((item, index) => {
	item.onclick = function () {
		barApi(index + 1)
	}
})
// ----------------------- 折线图 -----------------------
// 折线图请求风封装
function lineApi() {
	axios.get('/student/list').then(({data: {code, message, data}}) => {
		if(code === 0) {
			let lineData = {
				xAxisData: [],
				// 期望薪资
				salary: [],
				// 实际薪资
				truesalary: []
			}

			// 生成地图所需数据
			let chinaGeoCoordMap = { 上海: [121.4648, 31.2891] }
			let chinaDatas = []

			// 生成饼图所需数据
			let pieData = []
			data.forEach((item) => {
				// console.log(item)
				lineData.xAxisData.push(item.name)
				lineData.salary.push(item.salary)
				lineData.truesalary.push(item.truesalary)
				
				//  地图的数据生成
				chinaGeoCoordMap[item.city] = [item.jing, item.wei]
				chinaDatas.push([{name: item.city, value:0}])

				// 饼图的数据生成
				const index = pieData.findIndex(v => v.name === item.province)
				if (index >= 0) {
					pieData[index].value ++
				}else {
					pieData.push({
						value: 1,
						name: item.province
					})
				}
			})

			// 处理地图的数据
			// console.log(data)


			line(lineData)
			myMap(chinaGeoCoordMap, chinaDatas)
			pie(pieData)
		}
	})
}
lineApi()
function line({xAxisData, salary, truesalary}) {
const myChart = echarts.init(document.querySelector('.line'))
myChart.setOption({
  color: ['orangered', 'blue'],
  title: {
    text: '薪资 Salary'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: xAxisData
  },
  yAxis: {
    type: 'value',
  },
  dataZoom: [
    {
      type: 'slider', // 拖动条显示到轴的外面（默认就是slider类型）
      start: 0, // 拖动滑块起始位置（这是一个百分比）
      end: 50, // 拖动滑块结束位置（这是一个百分比）
    },
  ],
  series: [
    {
      name: '期望薪资',
      data: salary,
      type: 'line',
      symbol: 'none',
      smooth: true
    },
    {
      name: '实际薪资',
      data: truesalary,
      type: 'line',
      symbol: 'none',
      smooth: true
    }
  ]
})
}